const hre = require("hardhat");
const fs = require("fs");
const path = require("path");

async function main() {
  console.log("开始部署 Stockimprove 合约...");

  // 获取部署账户
  const [deployer] = await hre.ethers.getSigners();
  console.log("部署账户:", deployer.address);
  console.log("账户余额:", (await deployer.provider.getBalance(deployer.address)).toString());

  // 部署合约
  const Stockimprove = await hre.ethers.getContractFactory("Stockimprove");
  const stockimprove = await Stockimprove.deploy();
  
  // 等待部署完成（兼容新旧版本）
  let contractAddress;
  if (stockimprove.waitForDeployment) {
    // Hardhat 2.x / ethers v6
    await stockimprove.waitForDeployment();
    contractAddress = await stockimprove.getAddress();
  } else {
    // 旧版本 API
    await stockimprove.deployed();
    contractAddress = stockimprove.address;
  }
  
  console.log("Stockimprove 合约已部署到:", contractAddress);

  // 保存合约地址到文件
  const deploymentInfo = {
    contractAddress: contractAddress,
    deployer: deployer.address,
    network: hre.network.name,
    deployedAt: new Date().toISOString()
  };

  const outputPath = path.join(__dirname, "../deployment-info.json");
  fs.writeFileSync(outputPath, JSON.stringify(deploymentInfo, null, 2));
  console.log("部署信息已保存到:", outputPath);

  // 同时保存到前端可访问的位置
  const frontendConfigPath = path.join(__dirname, "../../frontend/src/config/contract.json");
  const frontendDir = path.dirname(frontendConfigPath);
  if (!fs.existsSync(frontendDir)) {
    fs.mkdirSync(frontendDir, { recursive: true });
  }
  fs.writeFileSync(frontendConfigPath, JSON.stringify(deploymentInfo, null, 2));
  console.log("合约配置已保存到前端目录:", frontendConfigPath);

  // 复制 ABI 到前端
  const artifactPath = path.join(__dirname, "../artifacts/contracts/Stockimprove.sol/Stockimprove.json");
  const artifact = JSON.parse(fs.readFileSync(artifactPath, 'utf8'));
  const abiPath = path.join(__dirname, "../../frontend/src/config/Stockimprove.json");
  fs.writeFileSync(abiPath, JSON.stringify(artifact, null, 2));
  console.log("合约 ABI 已复制到前端目录");
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

